package struts.core;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.core.action.Action;
import struts.core.form.ActionForm;
import struts.core.util.FormUtil;
import struts.core.util.StrutsXMLBean;

public class ActionServlet extends HttpServlet {

	public ActionServlet() {
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println(req.getServletPath());
		String actionPath = getPath(req.getServletPath());
		
		
		Map<String,StrutsXMLBean> strutsxml = (Map<String, StrutsXMLBean>) this.getServletContext().getAttribute("struts");
		
		StrutsXMLBean xmlbean = strutsxml.get(actionPath);
		ActionForm  form = FormUtil.getForm(xmlbean.getFormbeanClass(), req);
		
		String actionClass = xmlbean.getActionClass();
		Action action= null;
		String url = "";
		try{
			Class clazz = Class.forName(actionClass);
			action = (Action) clazz.newInstance();
			url=action.excute(req, resp, form, xmlbean.getForwards());
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("严重：action 错误");
		}
		
		RequestDispatcher dispatcher = req.getRequestDispatcher(url);
		dispatcher.forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
	private String getPath(String actionpath){
		
		return actionpath.split("\\.")[0];
	}
	

}
